package com.sxkf.template.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.jeecg.common.exception.SxkfException;
import org.jeecg.common.exception.SxkfExceptionEnum;
import org.jeecg.common.util.CheckEmptyUtil;
import com.sxkf.template.entity.FollowUser;
import com.sxkf.template.entity.User;
import com.sxkf.template.mapper.FollowUserMapper;
import com.sxkf.template.mapper.UserMapper;
import com.sxkf.template.service.FollowUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 张广成
 * @since 2024-11-06 10:16:40
 */
@Service
@Slf4j
public class FollowUserServiceImpl extends ServiceImpl<FollowUserMapper, FollowUser> implements FollowUserService {
    @Resource
    private FollowUserMapper followUserMapper;

    @Resource
    private UserMapper userMapper;


    @Override
    public IPage<User> selectFollowUser(String userId, String orderType, Integer pageNo, Integer pageSize) {
        if (CheckEmptyUtil.isEmpty(userId)) {
            throw new SxkfException(SxkfExceptionEnum.PARAM_ERROR);
        }
        // 校验页码和页面大小是否合法，避免不合理的请求
        if (pageNo <= 0 || pageSize <= 0) {
            throw new SxkfException(SxkfExceptionEnum.PARAM_ERROR);
        }
        Page<User> page = new Page<>(pageNo, pageSize);

        // 1. 查询 FollowUser 表，获取所有关注记录对应的用户 ID
        LambdaQueryWrapper<FollowUser> followQueryWrapper = new LambdaQueryWrapper<FollowUser>()
                .select(FollowUser::getFollowUserId)
                .eq(FollowUser::getUserId, userId);  // 你可以根据需要进行过滤
        if ("3".equals(orderType)) {
            // 按照关注时间升序排序
            followQueryWrapper.orderByAsc(FollowUser::getFollowTime);
        } else if ("2".equals(orderType)) {
            // 按照关注时间降序排序
            followQueryWrapper.orderByDesc(FollowUser::getFollowTime);
        } else {
            // 默认情况下按关注时间降序排序
            followQueryWrapper.orderByDesc(FollowUser::getFollowTime);
        }

        List<String> followUserIds = followUserMapper.selectList(followQueryWrapper).stream()
                .map(FollowUser::getFollowUserId) // 获取被关注者的 userId
                .collect(Collectors.toList());

        // 2. 根据这些 userIds 查询 Users 表
        if (!followUserIds.isEmpty()) {
            return userMapper.selectPage(page, new LambdaQueryWrapper<User>()
                    .in(User::getId, followUserIds));
        }
        return  null;
    }

    @Override
    public IPage<User> likeQuery(String userId, String nickName, String orderType, Integer pageNo, Integer pageSize) {
        if (CheckEmptyUtil.isEmpty(userId) || CheckEmptyUtil.isEmpty(nickName)) {
            throw new SxkfException(SxkfExceptionEnum.PARAM_ERROR);
        }
        // 校验页码和页面大小是否合法，避免不合理的请求
        if (pageNo <= 0 || pageSize <= 0) {
            throw new SxkfException(SxkfExceptionEnum.PARAM_ERROR);
        }
        Page<User> page = new Page<>(pageNo, pageSize);

        // 1. 查询 FollowUser 表，获取所有关注记录对应的用户 ID
        LambdaQueryWrapper<FollowUser> followQueryWrapper = new LambdaQueryWrapper<FollowUser>()
                .select(FollowUser::getFollowUserId)
                .eq(FollowUser::getUserId, userId);  // 你可以根据需要进行过滤
        if ("3".equals(orderType)) {
            // 按照关注时间升序排序
            followQueryWrapper.orderByAsc(FollowUser::getFollowTime);
        } else if ("2".equals(orderType)) {
            // 按照关注时间降序排序
            followQueryWrapper.orderByDesc(FollowUser::getFollowTime);
        } else {
            // 默认情况下按关注时间降序排序
            followQueryWrapper.orderByDesc(FollowUser::getFollowTime);
        }

        List<String> followUserIds = followUserMapper.selectList(followQueryWrapper).stream()
                .map(FollowUser::getFollowUserId) // 获取被关注者的 userId
                .collect(Collectors.toList());

        // 2. 根据这些 userIds 查询 Users 表
        if (!followUserIds.isEmpty()) {
            return userMapper.selectPage(page, new LambdaQueryWrapper<User>()
                    .in(User::getId, followUserIds)
                    .like(User::getNickName,nickName));
        }
        return  null;
    }

    @Override
    public IPage<User> getFans(String userId, String orderType, Integer pageNo, Integer pageSize) {
        if (CheckEmptyUtil.isEmpty(userId)) {
            throw new SxkfException(SxkfExceptionEnum.PARAM_ERROR);
        }
        // 校验页码和页面大小是否合法，避免不合理的请求
        if (pageNo <= 0 || pageSize <= 0) {
            throw new SxkfException(SxkfExceptionEnum.PARAM_ERROR);
        }
        Page<User> page = new Page<>(pageNo, pageSize);
        // 1. 查询 FollowUser 表，获取所有关注记录对应的用户 ID
        LambdaQueryWrapper<FollowUser> followQueryWrapper = new LambdaQueryWrapper<FollowUser>()
                .select(FollowUser::getUserId)
                .eq(FollowUser::getFollowUserId, userId);  // 你可以根据需要进行过滤
        if ("3".equals(orderType)) {
            // 按照关注时间升序排序
            followQueryWrapper.orderByAsc(FollowUser::getFollowTime);
        } else if ("2".equals(orderType)) {
            // 按照关注时间降序排序
            followQueryWrapper.orderByDesc(FollowUser::getFollowTime);
        } else {
            // 默认情况下按关注时间降序排序
            followQueryWrapper.orderByDesc(FollowUser::getFollowTime);
        }

        List<String> userIds = followUserMapper.selectList(followQueryWrapper).stream()
                .map(FollowUser::getUserId) // 获取被关注者的 userId
                .collect(Collectors.toList());

        // 2. 根据这些 userIds 查询 Users 表
        if (!userIds.isEmpty()) {
            return userMapper.selectPage(page, new LambdaQueryWrapper<User>()
                    .in(User::getId, userIds));
        }
        return  null;
    }

    @Override
    public IPage<User> likeQueryFans(String userId, String nickName, String orderType, Integer pageNo, Integer pageSize) {
        if (CheckEmptyUtil.isEmpty(userId) || CheckEmptyUtil.isEmpty(nickName)) {
            throw new SxkfException(SxkfExceptionEnum.PARAM_ERROR);
        }
        // 校验页码和页面大小是否合法，避免不合理的请求
        if (pageNo <= 0 || pageSize <= 0) {
            throw new SxkfException(SxkfExceptionEnum.PARAM_ERROR);
        }
        Page<User> page = new Page<>(pageNo, pageSize);

        // 1. 查询 FollowUser 表，获取所有关注记录对应的用户 ID
        LambdaQueryWrapper<FollowUser> followQueryWrapper = new LambdaQueryWrapper<FollowUser>()
                .select(FollowUser::getUserId)
                .eq(FollowUser::getFollowUserId, userId);  // 你可以根据需要进行过滤
        if ("3".equals(orderType)) {
            // 按照关注时间升序排序
            followQueryWrapper.orderByAsc(FollowUser::getFollowTime);
        } else if ("2".equals(orderType)) {
            // 按照关注时间降序排序
            followQueryWrapper.orderByDesc(FollowUser::getFollowTime);
        } else {
            // 默认情况下按关注时间降序排序
            followQueryWrapper.orderByDesc(FollowUser::getFollowTime);
        }

        List<String> userIds = followUserMapper.selectList(followQueryWrapper).stream()
                .map(FollowUser::getUserId) // 获取被关注者的 userId
                .collect(Collectors.toList());

        // 2. 根据这些 userIds 查询 Users 表
        if (!userIds.isEmpty()) {
            return userMapper.selectPage(page, new LambdaQueryWrapper<User>()
                    .in(User::getId, userIds)
                    .like(User::getNickName,nickName));
        }
        return  null;
    }

    @Override
    @Transactional
    public Boolean createFollowUser(FollowUser followUser) {
        if (CheckEmptyUtil.isEmpty(followUser)){
            throw new SxkfException(SxkfExceptionEnum.PARAM_ERROR);
        }
        followUser.setFollowTime(new Date());
        //先判断对方是否已关注过自己
        FollowUser user = followUserMapper.selectOne(new LambdaQueryWrapper<FollowUser>()
                .eq(FollowUser::getUserId, followUser.getFollowUserId())
                .eq(FollowUser::getFollowUserId, followUser.getUserId()));

        //查询关注者，并修改它的互关状态
        if (!CheckEmptyUtil.isEmpty(user)){
            if (user.getStatus().equals("1")){
                //查出对方的粉丝数+1
                User otherUser = userMapper.selectOne(new LambdaQueryWrapper<User>()
                        .select(User::getFansCount,User::getId)
                        .eq(User::getId, followUser.getFollowUserId()));

                //查出我的关注数+1
                User myUser = userMapper.selectOne(new LambdaQueryWrapper<User>()
                        .select(User::getFollowerCount,User::getId)
                        .eq(User::getId, followUser.getUserId()));
                otherUser.setFansCount(otherUser.getFansCount() + 1);
                myUser.setFollowerCount(myUser.getFollowerCount() + 1);
                //修改互关状态
                user.setIsMutual("1");
                followUser.setIsMutual("1");

                userMapper.updateById(myUser);
                userMapper.updateById(otherUser);
                followUserMapper.updateById(user);
                followUserMapper.insert(followUser);
                return true;
            }
        }
        else {
            //查出我的关注数+1
            User myUser = userMapper.selectOne(new LambdaQueryWrapper<User>()
                    .select(User::getFollowerCount,User::getId)
                    .eq(User::getId, followUser.getUserId()));
            myUser.setFollowerCount(myUser.getFollowerCount() + 1);
            userMapper.updateById(myUser);
            followUserMapper.insert(followUser);
            return true;
        }
        return false;
    }

    @Override
    public Boolean cancelFollowUser(FollowUser followUser) {
        if (CheckEmptyUtil.isEmpty(followUser)){
            throw new SxkfException(SxkfExceptionEnum.PARAM_ERROR);
        }
        //先判断关注用户是否已关注过自己
        FollowUser user = followUserMapper.selectOne(new LambdaQueryWrapper<FollowUser>()
                .eq(FollowUser::getUserId, followUser.getFollowUserId())
                .eq(FollowUser::getFollowUserId, followUser.getUserId()));

        //查询关注者，并修改它的互关状态
        if (!CheckEmptyUtil.isEmpty(user)){
            if (user.getStatus().equals("1")){
                //查出对方的粉丝数-1
                User otherUser = userMapper.selectOne(new LambdaQueryWrapper<User>()
                        .select(User::getFansCount,User::getId)
                        .eq(User::getId, followUser.getFollowUserId()));

                //查出我的关注数-1
                User myUser = userMapper.selectOne(new LambdaQueryWrapper<User>()
                        .select(User::getFollowerCount,User::getId)
                        .eq(User::getId, followUser.getUserId()));
                otherUser.setFansCount(otherUser.getFansCount() - 1);
                myUser.setFollowerCount(myUser.getFollowerCount() - 1);

                //修改互关状态
                user.setIsMutual("0");
                followUser.setIsMutual("0");
                userMapper.updateById(myUser);
                userMapper.updateById(otherUser);
                followUserMapper.updateById(user);
                followUserMapper.updateById(followUser);
                return true;
            }
        }
        else {
            //查出我的关注数-1
            User myUser = userMapper.selectOne(new LambdaQueryWrapper<User>()
                    .select(User::getFollowerCount,User::getId)
                    .eq(User::getId, followUser.getUserId()));
            myUser.setFollowerCount(myUser.getFollowerCount() - 1);
            userMapper.updateById(myUser);
            followUserMapper.updateById(followUser);
            return true;
        }
        return false;
    }
}
